package com.kabuda.hot100.普通数组.medium;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author kabuda
 * @create 2025-02-06 22:03
 * <p>
 * 给定一个整数数组 nums，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * [1,2,3,4,5,6,7]
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 * <p>
 * <p>
 * 向右轮转 4 步: [4,5,6,7,1,2,3]
 * 向右轮转 5 步: [3,4,5,6,7,1,2]
 * 向右轮转 6 步: [2,3,4,5,6,7,1]
 * 向右轮转 7 步: [1,2,3,4,5,6,7]
 */

//0->3
//1->4
//2->5
//3->6
//4->0
//5->1
//6->2

public class t189_轮转数组 {
    public static void main(String[] args) {
        int[] nums = new int[]{-1, -100, 3, 99};
        rotate(nums, 2);
        System.out.println(Arrays.toString(nums));
    }

    public static void rotate(int[] nums, int k) {

        //int n = nums.length;
        //int[] newArr = new int[n];
        //for (int i = 0; i < n; ++i) {
        //    newArr[(i + k) % n] = nums[i];
        //}
        //System.arraycopy(newArr, 0, nums, 0, n);

        int n = nums.length;
        Queue<Integer> queue = new LinkedList<>();
        //全部数据入队
        for (int i = n - 1; i >= 0; i--) {
            queue.offer(nums[i]);
        }
        //将出队的数据再入队
        while (k > 0) {
            queue.offer(queue.poll());
            k--;
        }
        int index = n - 1;
        while (!queue.isEmpty()) {
            nums[index--] = queue.poll();
        }
    }
}
